#------------------------------PowerCipher 1.1.3------------------------------
#------------By Neil Power, with help from Max Baker and Wyn Price------------
#----------------------------------(C) 2016-----------------------------------
#----------------------Licensed for non-commercial reuse----------------------

#NOTE: Not compatible with v0.9.8 or older, and
#therefore DOESN'T WORK with codes created with v0.9.8 or older

#For support or queries go to help page 1

#If there are any new features you would like added please email us

#Last updated at 16/09/2016
#New in this version (1.1.3):
    #Made the translated text fit in the screen nicely


from tkinter import * #Needed for the GUI
import random #Needed for optional random key generation
import os #Needed to open text file
import string #Needed to create a random string for testing
version = "1.1.3"
admin = "on"
defaultBackground = "#ED9332" #the default hex color for the background
buttonColor= "#FF0080" # the hex value for the button color
entryColor = "#32ED35" # the hex value for the entry box color

SUPPORTEDFILETYPES = [
".1ST", ".ABW",".ACT",".ADOC",".AIM",".ANS",".APKG",".APT",".ASC",".ASC",".ASCII",".ASE",".ATY",".AWP",".AWT",".AWW",
".BAD",".BBS",".BDP",".BDR",".BEAN",".BIB",".BIB",".BIBTEX",".BML",".BNA",".BOC",".BRX",".BTD",".BZABW",".CALCA",
".CHARSET",".CHART",".CHORD",".CNM",".COD",".CRWL",".CWS",".CYI",".DCA",".DGS",".DIZ",".DNE",".DOC",".DOCM",".DOCX",
".DOCXML",".DOCZ",".DOTM",".DOTX",".DOX",".DROPBOX",".DSC",".DVI",".DWD",".DX",".DXB",".DXP",".EIO",".EIT",".EMF",
".EML",".EMLX",".EMULECOLLECTION",".EPP",".ERR",".ERR",".ETF",".ETX",".EUC",".FADEIN.TEMPLATE",".FAQ",".FBL",".FCF",
".FDF",".FDR",".FDS",".FDT",".FDX",".FDXT",".FFT",".FLR",".FODT",".FOUNTAIN",".FPT",".FRT",".FWD",".FWDN",".GDOC",
".GMD",".GPD",".GPN",".GSD",".GTHR",".GV",".HBK",".HHT",".HS",".HWP",".HWP",".HZ",".IDX",".IIL",".IPF",".IPSPOT",
".JARVIS",".JIS",".JNP",".JOE",".JP1",".JRTF",".KES",".KLG",".KLG",".KNT",".KON",".KWD",".LATEX",".LBT",".LIS",
".LNT",".LOG",".LP2",".LST",".LST",".LTR",".LTX",".LUE",".LUF",".LWP",".LXFML",".LYT",".LYX",".MAN",".MBOX",".MCW",
".MD5.TXT",".ME",".MELL",".MELLEL",".MIN",".MNT",".MSG",".MW",".MWD",".MWP",".NB",".NDOC",".NFO",".NGLOSS",".NJX",
".NOTES",".NOW",".NWCTXT",".NWM",".NWP",".OCR",".ODIF",".ODM",".ODO",".ODT",".OFL",".OPENBSD",".ORT",".OTT",".P7S",
".PAGES",".PAGES-TEF",".PDPCMD",".PFS",".PFX",".PJT",".PLANTUML",".PMO",".PRT",".PRT",".PSW",".PU",".PVJ",".PVM",".PWD",
".PWDP",".PWDPL",".PWI",".PWR",".QDL",".QPF",".RAD",".README",".RFT",".RIS",".RPT",".RST",".RTD",".RTF",".RTFD",".RTX",
".RUN",".RZK",".RZN",".SAF",".SAFETEXT",".SAM",".SAM",".SAVE",".SCC",".SCM",".SCRIV",".SCRIVX",".SCT",".SCW",".SDM",
".SDOC",".SDW",".SE",".SESSION",".SGM",".SIG",".SKCARD",".SLA",".SLA.GZ",".SMF",".SMS",".SSA",".STORY",".STRINGS",".STW",
".STY",".SUB",".SUBLIME-PROJECT",".SUBLIME-WORKSPACE",".SXG",".SXW",".TAB",".TAB",".TDF",".TDF",".TEMPLATE",".TEX",
".TEXT",".TEXTCLIPPING",".THP",".TLB",".TM",".TMD",".TMV",".TPC",".TRELBY",".TVJ",".TXT",".U3I",".UNAUTH",".UNX",
".UOF",".UOT",".UPD",".UTF8",".UTXT",".VCT",".VNT",".VW",".WBK"".WEBDOC",".WN",".WP",".WP4",".WP5",".WP6",".WP7",
".WPA",".WPD",".WPD",".WPD",".WPL",".WPS",".WPS",".WPT",".WPT",".WPW",".WRI",".WSD",".WTT",".WTX",".XBDOC",".XBPLATE",
".XDL",".XDL",".XWP",".XWP",".XWP",".XY",".XY3",".XYP",".XYW",".ZABW",".ZRTF",".ZW",]

def tagree(textbox_text): #the I agree GUI function
    master = Tk() #sets the root to master
    master.config(bg=defaultBackground)
    master.minsize(width=500, height=100) #sets the size of the GUI
    master.wm_title("") #Sets the GUI box title to nothing
    textbox = Label(master, text=textbox_text, bg=defaultBackground, font=("Courier New", 12))#Makes a text box
    textbox.pack()#Adds the textbox to the GUI
    textbox.place(rely=0.1, relheight=0.3, relwidth=1)
    def destroy(): #defines the function 'destroy'
        master.destroy() #Destroyes the GUI box
    buttonblock = Button(master, text="I Agree", width=30, command=destroy,  bg="green", font=("Courier New", 12))
    buttonblock.pack()#Adds the button to the GUI
    buttonblock.place(relheight=0.1, relwidth=0.1, relx=0.37, rely=0.5)
    def agreementfunction(): #defines the function agreementfunction
        master.destroy() #Destroyes the GUI box
        agreement() #runs the agreement box
    buttonblock1 = Button(master, text="Click here\n for License \nAgreement", width=30, command=agreementfunction, bg="red", font=("Courier New", 12)) #Makes a button with "Click her for License Agreement" on it
    buttonblock1.pack()#Adds the button to the GUI
    buttonblock1.place(relheight=0.1, relwidth=0.1, rely=0.5, relx=0.53)
    def kill():#defines the kill function
        master.destroy()#destroyes the GUI box
        sys.exit()#exits the program
    buttonblock1 = Button(master, text="X", command=kill, bg="red") #makes a button with "Click to stop code" on it
    buttonblock1.pack() #Adds the button to the GUI
    buttonblock1.place(relheight=0.02, relwidth=0.015, relx=0.985)
    master.overrideredirect(True)
    master.geometry("{0}x{1}+0+0".format(master.winfo_screenwidth(), master.winfo_screenheight()))
    mainloop()#opens the GUI

def tinputGUI(textbox_text): #The GUI input function
    global varible
    master = Tk() #Sets the root to master
    master.config(background=defaultBackground)
    master.wm_title("") #Sets the GUI box title to nothing
    textbox = Label(master, text=textbox_text, bg=defaultBackground, font=("Courier New", 12)) #Makes a text box
    textbox.pack()#Adds the textbox to the GUI
    textbox.place(relwidth=1, rely=0.2, relheight=0.1)
    entrybox = Entry(master, bg=entryColor)#Makes a input box
    entrybox.pack()#Adds that inputbox to the GUI
    entrybox.focus_set() #sets the data collected from the input to the varible entrybox)
    entrybox.place(relx=0.45, rely=0.5, relheight=0.03, relwidth=0.1)
    def destroy(): #defines the function 'destroy'
        global varible #globalises the varible 'varible'
        varible =  entrybox.get() #gets the data entered by the user
        master.destroy()#destroyes the GUI box
    buttonblock = Button(master, text="Click when done", command=destroy, bg=buttonColor, font=("Courier New", 12))#Makes a button with the words "Click when done" on it
    buttonblock.pack()#Adds that button to the GUI
    buttonblock.place(relx=0.425, rely=0.55, relheight=0.05, relwidth=0.15)
    def kill():#defines the kill function
        master.destroy()#destroyes the GUI box
        sys.exit()#exits the program
    buttonblock1 = Button(master, text="X", command=kill, bg="red") #makes a button with "Click to stop code" on it
    buttonblock1.pack() #Adds the button to the GUI
    buttonblock1.place(relheight=0.02, relwidth=0.015, relx=0.985)
    master.overrideredirect(True)
    master.geometry("{0}x{1}+0+0".format(master.winfo_screenwidth(), master.winfo_screenheight()))
    mainloop()#opens the GUI

def tprint(textbox_text): #The GUI print function
    master = Tk() #Sets the root to master
    master.config(bg=defaultBackground)
    master.wm_title("") #Sets the GUI box title to nothing
    textbox = Label(master, text=textbox_text, bg= defaultBackground, font=("Courier New",12)) #Makes a text box
    textbox.pack()#Adds the textbox to the GUI
    textbox.place(relwidth = 1, rely=0.15)
    def destroy(): #defines the function 'destroy'
        master.destroy() #Destroyes the GUI box
    buttonblock = Button(master, text="Click to continue", command=destroy, font=("Courier New",12), bg=buttonColor)#Makes a button with the words "Click when done" on it
    buttonblock.pack()#Adds that button to the GUI
    buttonblock.place(relx=0.425, rely=0.55, relheight=0.05, relwidth=0.15)
    def kill():#defines the kill function
        master.destroy()#destroyes the GUI box
        sys.exit()#exits the program
    buttonblock1 = Button(master, text="X", command=kill, bg="red") #makes a button with "Click to stop code" on it
    buttonblock1.pack() #Adds the button to the GUI
    buttonblock1.place(relheight=0.02, relwidth=0.015, relx=0.985)
    master.overrideredirect(True)
    master.geometry("{0}x{1}+0+0".format(master.winfo_screenwidth(), master.winfo_screenheight()))
    mainloop()#opens the GUI


def tinput(textbox_text): #The function that calls the GUI input function
    global varible
    varible = ""
    tinputGUI(textbox_text)
    return varible

def getMode():#Gets and returns mode
    global admin
    mode = tinput("Type encrypt, decrypt or help: \nThe acceptable answers are:\n encrypt or e or decrypt or d or help or h")
    if mode.lower() == "admin":
        admin = "on"
        tprint("ADMIN MODE ACTIVATED")
    while mode not in "encrypt e decrypt d help h test t exit x".split():
            mode = tinput("Type encrypt, decrypt or help: \nThe acceptable answers are:\n encrypt or e or decrypt or d or help or h")
    if mode in "encrypt e decrypt d help h".split():#Checks if mode is valid
        return mode[0]

    elif mode.lower() == "test" or mode.lower() == "t":
        test()#Tests and exits
        return "x"

    elif mode.lower() == "admin":
        admin = "on"
        tprint("ADMIN MODE ACTIVATED")


    elif mode.lower() == "exit" or mode.lower() == "x":#Exits the program
                return mode[0]


def test():#Troubleshooting for devs - ignore this bit!
    message = ""
    for times in range(15):
        testIntOrStr = random.randint(0,1)
        if testIntOrStr == 1:
            message += random.choice(string.ascii_letters)
        else:
            message += str(random.randint(0,9))
    tprint("The original message was: \n" + message + "\n")
    key1 = random.randint(1, 9999999)
    key2 = random.randint(1, 9999999)
    key3 = getKey3(key1, key2)
    tprint("Key 1 is: \n" + str(key1) + "\n")
    tprint("Key 2 is: \n" + str(key2) + "\n")
    tprint("Key 3 is: \n" + str(key3) + "\n")
    emessage = translateMessage("e", message, key1, key2, key3, a, b)
    tprint("The encrypted message is: \n"+emessage+ "\n")
    messageSpace = ""
    for symbol in emessage:
        if symbol in string.ascii_letters:
            messageSpace = messageSpace + " "
        else:
            messageSpace = messageSpace + symbol
    tprint("The message without letters is: \n"+ messageSpace+ "\n")
    dmessage = translateMessage("d", messageSpace, key1, key2, key3, a, b)
    tprint("The decrypted message is: \n" + dmessage + "\n")
    if dmessage == message:
        tprint("The code is apparently working...")
    else:
        tprint("Something's wrong...")

def getMessage(mode):#Gets and returns message
    global fileUse#Creates a global variable to check if user is using file mode
    global fileName#Creates a global variable with the file name
    messageSpace = ""
    FileExtTest = ""
    messageChoice = tinput("Would you like to type a message (m) or use a file (f)? ")
    if messageChoice.lower() == "f":
        fileUse = True
        fileName = tinput("Enter the file name with the extension: ")
        for var in fileName:
            if var == ".":
                FileExtTest += " "
            else: FileExtTest += var
        FileExtTest = FileExtTest.split()
        if ("."+FileExtTest[-1].upper()) not in SUPPORTEDFILETYPES:
            tprint("FILE TYPE NOT SUPPORTED! Is the file a text file in a common format?")

            getMessage(mode)
        if ("."+FileExtTest[-1].upper()) in SUPPORTEDFILETYPES:
            file = open(fileName,"r")
            message = file.read()
    else: fileUse = False
    if mode[0] == "e" and messageChoice.lower() == "f":
        return message

    if mode[0] == "e" and messageChoice.lower() == "m":
        message = tinput("Enter your message")
        return message

    if mode[0] == "d":
        if messageChoice.lower() == "m":
            message = tinput("Enter your message")

        for symbol in message:#Replaces "-" in message with " "
            if symbol in string.ascii_letters:
                    messageSpace = messageSpace + " "
            else:
                    messageSpace = messageSpace + symbol
        return messageSpace

def getKey1(mode):#Gets and returns key1
    while True:
        if mode[0] == "e":
            key1 = tinput("""Enter the first key number,
type 'r' to get a random one or type 't' to use the text file: """)

        if mode[0] == "d":
            key1 = tinput("Enter the first key number or type 't' to use the text file: ")

        if str(key1) == "t":
            keyMod = ""
            keyTxt = open("Key1.txt","r")#Opens key1 from txt file
            keyTxtList = list(keyTxt.read())
            for x in keyTxtList:
                if x == "O":
                    keyMod += "4"
                else: keyMod += x
            return int(keyMod)

        if str(key1) == "r" and mode[0] == "e":
            randKey1 = random.randint(0, 999999)#Randomly generates key
            tprint("Your first key is " + str(randKey1))
            return int(randKey1)

        if key1.isalpha():
            tprint("Invalid Key.\n")

        elif (int(key1) >= 0):#Checks key1
            return int(key1)

        else:
            tprint("Invalid Key.\n")


def getKey2(mode):#Gets and returns key2
    while True:
        if mode[0] == "e":
            key2 = tinput("""Enter the second key number,
type 'r' to get a random one or type 't' to use the text file: """)

        if mode[0] == "d":
            key2 = tinput("Enter the second key number or type 't' to use the text file: ")

        if str(key2) == "t":
            keymod = ""
            keyTxt = open("Key2.txt","r")#Opens key2 from txt file
            keyTxtList = list(keyTxt.read())
            for x in keyTxtList:
                if x == "O":
                    keymod += "4"
                else: keymod += x
            return int(keymod)

        if str(key2) == "r" and mode[0] == "e":
            randKey2 = random.randint(0, 999999)#Randomly generates key
            tprint("Your second key is " + str(randKey2))
            return int(randKey2)

        if key2.isalpha():
            tprint("Invalid Key.\n")

        elif (int(key2) >= 0):#Checks key2
            return int(key2)

        else:
            tprint("Invalid Key.\n")



def getKey3(key1, key2):#Generates a third key based on the other two
    key3 = (key1 + key2)/2
    return int(round(key3, 0))#Returns key3 as int to round to 0dp


def translateMessage(mode, message, key1, key2, key3, a, b):#Translates message into encrypted or decrypted form
    translated = ""
    staticKey1 = key1#Creates a version of key1 that doesn't change
    staticKey2 = key2#Creates a version of key2 that doesn't change
    staticKey3 = key3#Creates a version of key3 that doesn't change

    if mode[0] == "e":#Encrypts message

        for symbol in message:#Runs through each symbol in message
            key1 += staticKey2#Increases key1 by key2
            key2 += staticKey3#Increases key2 by key3
            key3 += staticKey1#Increases key3 by key1
            key1, key2 = key2, key1#Swaps keys
            key2, key3 = key3, key2#Swaps keys
            num = ord(symbol)#Converts symbol in message to ASCII number
            num = eval(a)#Encryption code hidden for security purposes
            inbetween = random.choice(string.ascii_uppercase)
            translated = translated + str(num) + inbetween#Adds encrypted to message and the varible 'inbetween' between each symbol
        translated = translated[0:(int(len(translated))-1)]
    if mode[0] == "d":#Decrypts message
        messageList = message.split()#Splits message into the blocks of numbers that are the symbols

        for symbol in messageList:#Runs through each symbol in message
            key1 += staticKey2#Increases key1 by key2
            key2 += staticKey3#Increases key2 by key3
            key3 += staticKey1#Increases key3 by key1
            key1, key2 = key2, key1#Swaps keys
            key2, key3 = key3, key2#Swaps keys
            num = eval(b)#Decryption code hidden for security purposes
            translated = translated + chr(num)#Adds decrypted to message

    return translated

def programHelp():#Print help on how to use program

        tprint("""--------------------------------PROGRAM HELP:--------------------------------\n
    To use this program, first select your mode.
        Encrypt: Encrypts a text message using two keys
        Decrypt: Decrypts a text message if you know the two keys
        Help: Opens the help menu\n""")
        tprint("""Then, chose whether to use a text file or enter your message.
    if you chose file mode, you are prompted to select a file which will be encrypted.
    WARNING: The file will be overwritten with encrypted text and will be unrecoverable without the keys.
    It is advised to save a copy of the original file.
    If you chose message mode, enter your message. This can be anything you like,
    as long as it doesn't contain blank lines.\n""")
        tprint("""You are then prompted to enter the first key.
        If you are in encrypt mode, you also have the option
        to randomly generate the second key. Just type 'r'.
        Remember this key, as you'll need it to decrypt the message.""")
        tprint("""You are then prompted to enter the second key.
        If you are in encrypt mode, you also have the option
        to randomly generate the second key. Just type 'r'.
        Remember this key, as you'll need it to decrypt the message.\n""")
        tprint("Your encrypted/decrypted message is then displayed.\n")
        tprint("""You then have the option to save the result to a text file.
    If you type yes, then the result will be saved in the same folder as the program is in.\n""")
        tprint("If you want to run the program again, type 'y'.")
        tprint("Simple!\n")
        tprint("""For any other issues, please email npower016@gmail.com\n""")


def howItWorks():#Prints help on how program works

        tprint("""--------------------------------HOW IT WORKS:--------------------------------\n
    PowerCipher works using some complicated maths,
    but crucially using the chr() and ord() functions.
    These allow the message to be converted into the ASCII key,
    which is a series of numbers used to represent symbols.
    These numbers are then encrypted by the two keys using the following method:""")
        tprint("""
        XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
        [Blocked for security reasons]
        XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n""")
        tprint("""and then printed.
    Decrypting does the exact opposite.\n
    Simple!\n""")

def programLicense():#Prints license for program

        tprint("""
A. HISTORY OF THE SOFTWARE
==========================
PowerCipher, formerly NeilCipher, was created in 2015 by Neil Power,
although it also includes contributions from
Max Baker and Wyn Price. There have been a number of releases, and the
latest one is currently 1.1.0

B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING POWERCIPHER
====================================================================

POWERCIPHER LICENSE
-------------------
Copyright (c) 2016, Neil Power

All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.""")
        tprint(""" SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS BEAR NO LIABILITY WHATSOEVER FOR ANY DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES AS A RESULT OF
MESSAGES BEING DECRYPTED BY A THIRD PARTY. THE AUTHORS DO NOT
GUARANTEE THAT MESSAGES ENCRYPTED USING THIS SOFTWARE WILL
BE SECURE.THIS PROGRAM IS DESIGNED FOR INFORMAL USE ONLY,
AND SHOULD NOT BE USED TO ENCRYPT CONFIDENTIAL INFORMATION.\n
THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS. REUSE WITH MODIFICATION OF THIS PROGRAM IS\
PERMITTED BUT THE ORIGINAL AUTHOUS MUST BE CREDITED AND A
FULL LIST OF CHANGES INCLUDED IN THE PROGRAM""")



def programCredits():#Prints credits

        tprint("-----------------------------------CREDITS-----------------------------------\n")
        tprint("This program was written by:\n")

        tprint("NEIL POWER\n")

        tprint("With assistance and testing provided by:\n")

        tprint("MAX BAKER\n")

        tprint("and\n")

        tprint("WYN PRICE\n")

def programCopyright():#Prints Copyright

        tprint("----------------------------------COPYRIGHT----------------------------------\n")
        tprint("""This program was made by Neil Power, with help from Max Baker and Wyn Price,
    and is licensed for non-commercial (or personal) reuse with or without modification.
    I request that you retain the author's name if modifying this program.
    Permission to use commercially can be obtained
    from Neil Power (npower016@gmail.com)
    Thank you for your cooperation with these requests,
    and I hope that you enjoyed using this program.
    Please contact the following email for support or questions:\n
    Neil Power (npower016@gmail.com) \n""")

def helpScreen():#Runs help commands
    helpChoice = ""
    tprint("Welcome to help for PowerCipher" + str(version) + "\n")
    while helpChoice not in "1 2 3 4 5 6 7 cancel c".split():
        tprint("""1) Get help on using this program
2) See how this program works
3) View the Python software license
4) View the PowerCipher software license
5) View the credits for this program
6) View the credits for Python
7) View the copyright for this program
8) View the copyright for Python
Or type cancel to return to the main menu.""")

        helpChoice = tinput("Please enter the number for your choice (or cancel): ")

        if helpChoice == "1":
            programHelp()

        if helpChoice == "2":
            howItWorks()

        if helpChoice == "3":

            license()

        if helpChoice == "4":
            programLicense()

        if helpChoice == "5":
            programCredits()

        if helpChoice == "6":
            credits()

        if helpChoice == "7":
            programCopyright()

        if helpChoice == "8":
            copyright()

def agreement():
            tprint("""

POWERCIPHER LICENSE
-------------------
Copyright (c) 2016, Neil Power

All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.""")
            tagree(""" SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS BEAR NO LIABILITY WHATSOEVER FOR ANY DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES AS A RESULT OF
MESSAGES BEING DECRYPTED BY A THIRD PARTY. THE AUTHORS DO NOT
GUARANTEE THAT MESSAGES ENCRYPTED USING THIS SOFTWARE WILL
BE SECURE.THIS PROGRAM IS DESIGNED FOR INFORMAL USE ONLY,
AND SHOULD NOT BE USED TO ENCRYPT CONFIDENTIAL INFORMATION.\n
THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS. REUSE WITH MODIFICATION OF THIS PROGRAM IS\
PERMITTED BUT THE ORIGINAL AUTHOUS MUST BE CREDITED AND A
FULL LIST OF CHANGES INCLUDED IN THE PROGRAM""","true")
formula= "105 110 116 40 40 40 40 40 40 110 117 109 42 107 101 121 49 41 43 107 101 121 50 41 45 107 101 121 51 41 45 107 101 121 49 41 43 107 101 121 50 41 45 107 101 121 51 41".split()
a = ""
for p in formula:
    a += chr(int(p))

def saveResult(resultChoice, message, key1, key2, translatedMessage, mode):#Option to write result to txt file
    if resultChoice[0] == "y":
        saveChoice = " "
        messageSpace = ""
        while str(saveChoice[0]) != "1" and str(saveChoice[0]) != "2":
            saveChoice = tinput("""Type 1 to save the full result,
or 2 to just save the translated message: """)
            if mode[0] == "e":
                for symbol in translatedMessage:#Replaces " " in message with "-"
                    if symbol == " ":
                        messageSpace = messageSpace + random.choice(string.ascii_uppercase)
                    else:
                        messageSpace = messageSpace + symbol
                translatedMessage = messageSpace
            if saveChoice[0] == "1":
                with open('TranslatedMessage.txt', 'w') as file:#Creates a txt file and writes result in it
                    file.write(BANNER)
                    file.write(message)
                    file.write("\n with keys "+str(key1)+" and "+str(key2)+" is \n")
                    file.write(translatedMessage)
            if saveChoice[0] == "2":
                with open('TranslatedMessage.txt', 'w') as file:#Creates a txt file and writes result in it
                    file.write(translatedMessage)

        tprint("The result has been saved in TranslatedMessage.txt")
        openChoice = ""
        while openChoice != "y" and openChoice != "n":
            openChoice = tinput("Would you like to open it? (y/n)")
            if openChoice == "y":
                os.startfile("TranslatedMessage.txt")
            else:
                openChoice = tinput("Would you like to open it? (y/n)")

formula= "105 110 116 40 40 40 40 40 40 105 110 116 40 115 121 109 98 111 108 41 43 107 101 121 51 41 45 107 101 121 50 41 43 107 101 121 49 41 43 107 101 121 51 41 45 107 101 121 50 41 47 107 101 121 49 41".split()
b = ""
for p in formula:
    b += chr(int(p))

def end():
    endChoice = ""
    endChoice = tinput("Would you like to end this program? (y/n)")
    if endChoice[0] == "y":
        sys.exit()

    if endChoice[0] != "y":
        main()


def main():
    global fileUse #needed to see a file has been used
    mode = getMode()#Gets mode
    if mode[0] == "x":
        end()
    if mode[0] == "h":#Prints help screen
        helpScreen()
    elif mode[0] in "e d".split():
        message = getMessage(mode)#Gets message, and if decrypting replaces "-" in message with " "
        key1 = getKey1(mode)#Gets key1
        key2 = getKey2(mode)#Gets key2
        key3 = getKey3(key1, key2)#Gets key3
        translatedMessage = translateMessage(mode, message, key1, key2, key3, a, b)
        pp=0
        translatedmessageBig=""
        if len(translatedMessage) >= 120:
            for x in translatedMessage:
                pp+=1
                if pp == 120:
                    pp=0
                    translatedmessageBig += x + "\n"
                else: translatedmessageBig += x
            tprint("Your translated text is: \n" + translatedmessageBig)
        else: tprint("Your translated text is: \n" + translatedMessage)#Prints final message
        if fileUse == True:
            file = open(fileName,"w")
            file.write(translatedMessage)
            tprint("Saved to " + fileName)
            end()
        if fileUse == False:
            printnormal = tinput("Do you want the translated text to be printed on the normal Python Interpreter? (y/n)")
            if printnormal.lower() not in ["yes","y","no","n"]:
                tprint("Ill take that as a no.")
            elif printnormal in ["yes","y"]:
                print(translatedMessage)
            resultChoice = tinput("Would you like to save the message in a text file? (y/n)")
            saveResult(resultChoice, message, key1, key2, translatedMessage, mode)
            end()

BANNER = """-------------------------------PowerCipher """+version+"""------------------------------
------------By Neil Power, with help from Max Baker and Wyn Price------------
----------------------------------(C) 2016-----------------------------------
By using this program you agree to the License Agreement.\n"""

tagree(BANNER)
main()
